package com.wsoft.hr.pm.manager;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsoft.constant.redis.HrPmRedisKeyConstant;
import com.wsoft.constant.redis.RedisKeyConstant;
import com.wsoft.core.annotation.GetRedisCache;
import com.wsoft.core.service.RedisService;
import com.wsoft.entity.BaseEntity;
import com.wsoft.hr.pm.entity.HrPmTemplateEntity;
import com.wsoft.hr.pm.mapper.HrPmTemplateMapper;
import com.wsoft.hr.pm.query.template.TemplateListQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author z001
 * @Date 2025年02月17日 15:06:35
 */
@Slf4j
@Service
public class HrPmTemplateManager extends ServiceImpl<HrPmTemplateMapper, HrPmTemplateEntity> {

    @Resource
    private RedisService redisService;

    /**
     * 根据templateName 查询已启用的模版
     * @param templateName
     * @return
     */
    public HrPmTemplateEntity getEnableTemplateName(String templateName){
        QueryWrapper<HrPmTemplateEntity> query = new QueryWrapper<>();
        query.lambda().eq(HrPmTemplateEntity::getName,templateName)
                .eq(HrPmTemplateEntity::getState,2);
        return getOne(query);
    }


    @GetRedisCache(type = HrPmRedisKeyConstant.TEMPLATE_INFO,
            expire_sec = HrPmRedisKeyConstant.EXPIRED,
            value = RedisKeyConstant.REDIS_SELF)
    public HrPmTemplateEntity getById(Long id){
        return super.getById(id);
    }

    /**
     * 分页查询
     * @param param
     * @return
     */
    public List<HrPmTemplateEntity> list(TemplateListQuery param){
        QueryWrapper<HrPmTemplateEntity> query = new QueryWrapper<>();
        query.lambda().like(StrUtil.isNotBlank(param.getName()),HrPmTemplateEntity::getName,param.getName())
                .eq(null != param.getState(),HrPmTemplateEntity::getState,param.getState())
                .orderByDesc(BaseEntity::getCreateTime);
        return list(query);
    }


    @Override
    public boolean updateById(HrPmTemplateEntity entity){
        boolean b = super.updateById(entity);
        if(b){
            redisService.del(HrPmRedisKeyConstant.TEMPLATE_INFO + entity.getId());
        }
        return b;
    }


    /**
     * 移除
     * @param id
     * @return
     */
    public boolean removeById(Long id){
        boolean b = super.removeById(id);
        if(b){
            redisService.del(HrPmRedisKeyConstant.TEMPLATE_INFO + id);
        }
        return b;
    }

    @Override
    public boolean saveOrUpdate(HrPmTemplateEntity entity){
        Long id = entity.getId();
        boolean b = super.saveOrUpdate(entity);
        if(b && null!= id){
            redisService.del(HrPmRedisKeyConstant.TEMPLATE_INFO + entity.getId());
        }
        return b;
    }



}
